package com.business.sys.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.business.common.dto.R;
import com.business.redis.constant.RedisKeyConstant;
import com.business.redis.utils.RedisUtil;
import com.business.sys.entity.DictionaryItem;
import com.business.sys.service.DictionaryItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 字典项表: 后端controller类
 *
 * @author chenjiehong
 * @date 2019-04-28 15:03:17
 * @since 1.0
 */
@RestController
@RequestMapping(value = "/dictionary")
public class DictionaryController {


    @Autowired
    private DictionaryItemService sysDictionaryItemServiceImpl;

    /**
     * 查询字典项表
     *
     * @param type
     * @date 2019-04-28 15:03:17
     */
    @GetMapping("/query")
    @ResponseBody
    public R<List<DictionaryItem>> query(@RequestParam("type") Integer type) {
        String redisKey = String.format(RedisKeyConstant.DICTIONARY_ITEM_QUERY, type);
        if (!RedisUtil.hasKey(redisKey)) {
            List<DictionaryItem> r = sysDictionaryItemServiceImpl.query(type);
            RedisUtil.setValue(redisKey, r);
            return R.success(r);
        } else {
            return R.success(RedisUtil.getArray(redisKey, DictionaryItem.class));
        }
    }

    /**
     * 查询字典项表
     * 多项一起查询
     *
     * @param params
     * @date 2019-04-28 15:03:17
     */
    @GetMapping("/queryList")
    @ResponseBody
    public R<List<DictionaryItem>[]> queryList(@RequestParam Integer[] types) {
        List<DictionaryItem>[] result = new List[types.length];
        for (int i = 0; i < types.length; i++) {
            Integer type = types[i];
            R<List<DictionaryItem>> r = query(type);
            if (r.getCode() == 0) {
                result[i] = r.getData();
            } else {
                result[i] = new ArrayList<>();
            }
        }
        return R.success(result);
    }


    @GetMapping("/queryById")
    @ResponseBody
    public R<DictionaryItem> queryById(@RequestParam Integer id) {
        String redisKey = String.format(RedisKeyConstant.DICTIONARY_ITEM_QUERY_BY_ID, id);
        if (!RedisUtil.hasKey(redisKey)) {
            DictionaryItem r = sysDictionaryItemServiceImpl.queryById(id);
            RedisUtil.setValue(redisKey, r);
            return R.success(r);
        } else {
            return R.success(RedisUtil.getObject(redisKey, DictionaryItem.class));
        }
    }

}